package com.example.myblog.service;

import com.example.myblog.NotFoundException;
import com.example.myblog.dao.BlogDao;
import com.example.myblog.entity.Blog;
import com.example.myblog.entity.Type;
import com.example.myblog.util.MarkdownUtils;
import com.example.myblog.util.MyBeanUtils;
import com.example.myblog.viewobject.BlogQuery;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.*;
import java.util.*;

/**
 * Created by asus on 2020/5/29 13:49
 */
@Service
public class BlogService {

    @Autowired private BlogDao blogDao;

    @Transactional
    public Blog getBlog(Long id){
        return blogDao.getOne(id);
    }

    //查看id是?的博客，对博客详情的内容文本转成html格式，用到MarkdownUtils工具类
    //拷贝到新对象是为了我们数据库的文本保持原来的markdown文本
    @Transactional
    public Blog getAndConvert(Long id){
        Blog blog = blogDao.getOne(id);
        if(blog == null){
            throw new NotFoundException("该博客不存在");
        }
        Blog b = new Blog();
        BeanUtils.copyProperties(blog,b);
        String content = b.getContent();
        b.setContent(MarkdownUtils.markdownToHtmlExtensions(content));
        blogDao.updateViews(id);
        return b;
    }

    //分页+动态组合查询
    @Transactional
    public Page<Blog> listBlog(Pageable pageable, BlogQuery blogQuery){
        return blogDao.findAll(new Specification<Blog>(){
            @Override
            public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicates = new ArrayList<>();
                if(!"".equals(blogQuery.getTitle()) && blogQuery.getTitle() != null){
                    predicates.add(criteriaBuilder.like(root.<String>get("title"),"%"+blogQuery.getTitle()+"%"));
                }
                if(blogQuery.getTypeId() != null){
                    predicates.add(criteriaBuilder.equal(root.<Type>get("type").get("id"),blogQuery.getTypeId()));
                }
                if(blogQuery.isRecommend()){
                    predicates.add(criteriaBuilder.equal(root.<Boolean>get("recommend"),blogQuery.isRecommend()));
                }
                //把List<Predicate>转成数组
                query.where(predicates.toArray(new Predicate[predicates.size()]));
                return null;
            }
        },pageable);
    }

    //分页查找
    @Transactional
    public Page<Blog> ListBlog(Pageable pageable){
        return blogDao.findAll(pageable);
    }

    @Transactional
    public Blog saveBlog(Blog blog){
        if (blog.getId() == null){
            blog.setCreateTime(new Date());
            blog.setUpdateTime(new Date());
            blog.setViews(0);
        }else {
            blog.setUpdateTime(new Date());
        }
        return blogDao.save(blog);
    }

    @Transactional
    public Blog updateBlog(Long id,Blog blog){
        Blog b = blogDao.getOne(id);
        if(b == null){
            throw new NotFoundException("博客不存在");
        }
        //过滤blog属性值为空的属性
        BeanUtils.copyProperties(blog,b, MyBeanUtils.getNullPropertyNames(blog));
        b.setUpdateTime(new Date());
        return blogDao.save(b);
    }

    @Transactional
    public void deleteBlog(Long id){
        blogDao.deleteById(id);
    }

    @Transactional
        public List<Blog> ListRecommendBlogTop(Integer size){
            Sort sort = Sort.by(Sort.Direction.DESC,"updateTime");
            Pageable pageable = PageRequest.of(0,size,sort);
            return blogDao.findTop(pageable);
    }

    //search，根据页面传来的字符进行搜索，显示出搜索出的博客
    @Transactional
    public Page<Blog> ListBlog(String query,Pageable pageable){
        return blogDao.findByQuery(query,pageable);
    }

    //博客首页展示
    @Transactional
    public Page<Blog> listBlog(Long tagId,Pageable pageable){
        return blogDao.findAll(new Specification<Blog>() {
            @Override
            public Predicate toPredicate(Root<Blog> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                Join join = root.join("tags");
                return criteriaBuilder.equal(join.get("id"),tagId);
            }
        },pageable);
    }

    //时间轴展示
    public Map<String,List<Blog>> archivesBlog() {
        List<String> years = blogDao.findGroupYear();
        Map<String,List<Blog>> map = new LinkedHashMap<>();
        for (String year : years){
            map.put(year,blogDao.findByYear(year));
        }
        return map;
    }

    public Long countBlog(){
        return blogDao.count();
    }
}
